package com.innovation.ic.im.end.web.thread;

import com.alibaba.fastjson.JSON;
import com.innovation.ic.im.end.base.model.im_erp9.UserGroupMessage;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.enums.AvailableStatusEnum;
import com.innovation.ic.im.end.base.service.helper.ServiceImplHelper;
import com.innovation.ic.im.end.base.service.im_erp9.RefUserGroupAccountService;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import com.innovation.ic.im.end.base.vo.im_erp9.SendUserGroupMessageVo;
import com.innovation.ic.im.end.web.endpoint.UserGroupEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import javax.websocket.Session;
import java.util.Map;
import java.util.Set;

/**
 * 将群成员修改群名消息保存到user_group_message及user_group_message_receiver表中
 */
public class SaveUserGroupNameUpdateMessageThread extends AbstractThread implements Runnable {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String exchange;

    private Map<String, Set<UserGroupEndpoint>> onlineUserGroupMap;

    public SaveUserGroupNameUpdateMessageThread(UserGroupMessage userGroupMessage, String exchange, Map<String, Set<UserGroupEndpoint>> onlineUserGroupMap) {
        this.userGroupMessage = userGroupMessage;
        this.exchange = exchange;
        this.onlineUserGroupMap = onlineUserGroupMap;
    }

    @Override
    public void run() {
        // 更新最近联系时间
        RefUserGroupAccountService refUserGroupAccountService = ServiceImplHelper.getRefUserGroupAccountService();
        refUserGroupAccountService.updateLastContactTimeByUserGroupId(userGroupMessage.getUserGroupId());

        // 保存自定义群组消息
        userGroupMessage.setFromUserAvailable(AvailableStatusEnum.AVAILABLE.getCode());
        ServiceResult<Integer> integerServiceResult = ServiceImplHelper.getUserGroupMessageService().saveUserGroupMessage(this.userGroupMessage);
        Integer userGroupMsgId = integerServiceResult.getResult();
        userGroupMessage.setId(userGroupMsgId);

        // 保存自定义群组修改群名的未读消息
        SaveUserGroupNameUpdateMsgReceiverThread saveUserGroupNameUpdateMsgReceiverThread = new SaveUserGroupNameUpdateMsgReceiverThread(userGroupMsgId, userGroupMessage, exchange);
        threadPoolManager.execute(saveUserGroupNameUpdateMsgReceiverThread);

        // 向自定义群组的所有在线用户推送补充了消息id的数据
        Set<UserGroupEndpoint> userGroupEndpointSet = onlineUserGroupMap.get(userGroupMessage.getUserGroupId().toString());
        if(userGroupEndpointSet != null && userGroupEndpointSet.size() > 0){
            for (UserGroupEndpoint userGroupEndpoint : userGroupEndpointSet) {
                Session theSession = userGroupEndpoint.session;
                synchronized (theSession) {
                    if (theSession.isOpen()) {
                        SendUserGroupMessageVo sendUserGroupMessageVo = new SendUserGroupMessageVo();
                        BeanUtils.copyProperties(userGroupMessage, sendUserGroupMessageVo);
                        sendUserGroupMessageVo.setToUserRealName(getUserRealNameByAccount(userGroupEndpoint.getUsername()));
                        sendUserGroupMessageVo.setUserGroupMessageId(userGroupMsgId.toString());
                        logger.info("sendUserGroupMessageVo=[{}]", sendUserGroupMessageVo);
                        theSession.getAsyncRemote().sendText(JSON.toJSONString(sendUserGroupMessageVo));
                    }
                }

                logger.info("用户【" + userGroupMessage.getFromUserAccount() + "】向自定义群组【"
                        + userGroupMessage.getUserGroupId() + "】中的用户【" + userGroupEndpoint.username
                        + "】发送系统消息【" + userGroupMessage.getContent() + "】");
            }
        }
    }
}